package com.wgn.reportquery.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.transform.TransformerException;

import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.wgn.reportquery.cons.Const;
import com.wgn.reportquery.dao.ImportDaoImple;
import com.wgn.reportquery.http.QueryHttpClient;
import com.wgn.reportquery.model.Hospital;
import com.wgn.reportquery.model.Report;
import com.wgn.reportquery.model.Reportdata;
import com.sun.org.apache.xpath.internal.XPathAPI;

public class Importer {
	

	public Importer() {
	
	}

	public List<Reportdata> getData(InputStream ins, ImportDaoImple im,
			String fileName,String username) throws Exception {
		InputSource inputSource = new InputSource();
		inputSource.setByteStream(ins);
		// 创建一个解析器
		DOMParser parser = new DOMParser();
		// 解析HTML文件
		// parser.parse("file:///" + file.getAbsolutePath());
		parser.parse(inputSource);
		// 获取解析后的DOM树
		Node node = parser.getDocument();
		Report r = getReport(node);
		String reportdate = r.getDate();
		String rNo = r.getNo();

		List<Reportdata> rowsList = new ArrayList<Reportdata>();
	
		
		

			
		
//		im.delete("DELETE FROM DATAS where REPORTNO='" + rNo + "'");
		// 通过getElementsByTagName获取Node
		NodeList nodeList = XPathAPI.selectNodeList(node, "//TBODY/TR");// 每行的内容

		for (int i = 0; i < nodeList.getLength(); i++) {
			Element e = (Element) nodeList.item(i);
			String content = e.getTextContent();
			if (content.indexOf("报告备注") > -1)
				break;
			String[] contents = content.replace("\\t", "").replace(">", "")
					.replace("<", "").replace("↓", "").replace("↑", "")
					.split("\r|\n");
			Reportdata reportdata = new Reportdata();
			reportdata.setReportdate(reportdate);
			reportdata.setReportNo(rNo);
			int index = 0;
			for (String s : contents) {
				s = s.trim();
				if (s.length() != 0) {
					switch (index) {
					case 0:
						reportdata.setNo(s);
						break;
					case 1:
						reportdata.setInfo(s);
						break;
					case 2:
						reportdata.setVal(s);
						break;
					case 3:
						reportdata.setScope(s);
						break;
					default:
						break;

					}
					index++;

				}
				;// 把数据填充到list里面,【0编号，1描述,2值,3范围】，如[111,测试项目,11,11-22]

			}
			rowsList.add(reportdata);
			// System.out.println(content);
			// System.out.println("-----------");

		}

		System.out.println("读取" + fileName + "成功,数据条数" + rowsList.size());
		return rowsList;
	}

	public File[] getHtmls(String dir) {
		File fileDir = new File(dir);
		File[] files = null;
		if (fileDir.isDirectory()) {
			files = fileDir.listFiles();
			System.out.println(dir + "文件夹下文件有:");
			for (File f : files) {
				System.out.println(f.getName());
			}
		} else {
			System.out.println(dir + "不是一个文件夹");
		}
		return files;
	}
/*
	public List<Reportdata> getData(File file, ImportDaoImple im)
			throws Exception {

		// 创建一个解析器
		DOMParser parser = new DOMParser();
		// 解析HTML文件
		parser.parse("file:///" + file.getAbsolutePath());
		// 获取解析后的DOM树
		Node node = parser.getDocument();
		Report r = getReport(node);
		String reportdate = r.getDate();
		String rNo = r.getNo();

		List<Reportdata> rowsList = new ArrayList<Reportdata>();
		if (im.exists("select * from DATAS where REPORTNO='" + rNo + "'",null)) {
			System.out.println(file.getName() + "存在数据，不导入,报告编号" + rNo);
			return rowsList;
		}
	
			
		
		im.delete("DELETE FROM DATAS where REPORTNO='" + rNo + "'");
		// 通过getElementsByTagName获取Node
		NodeList nodeList = XPathAPI.selectNodeList(node, "//TBODY/TR");// 每行的内容

		for (int i = 0; i < nodeList.getLength(); i++) {
			Element e = (Element) nodeList.item(i);
			String content = e.getTextContent();
			if (content.indexOf("报告备注") > -1)
				break;
			String[] contents = content.replace("\\t", "").replace(">", "")
					.replace("<", "").replace("↓", "").replace("↑", "")
					.split("\r|\n");
			Reportdata reportdata = new Reportdata();
			reportdata.setReportdate(reportdate);
			reportdata.setReportNo(rNo);
			int index = 0;
			for (String s : contents) {
				s = s.trim();
				if (s.length() != 0) {
					switch (index) {
					case 0:
						reportdata.setNo(s);
						break;
					case 1:
						reportdata.setInfo(s);
						break;
					case 2:
						reportdata.setVal(s);
						break;
					case 3:
						reportdata.setScope(s);
						break;
					default:
						break;

					}
					index++;

				}
				;// 把数据填充到list里面,【0编号，1描述,2值,3范围】，如[111,测试项目,11,11-22]

			}
			rowsList.add(reportdata);
			// System.out.println(content);
			// System.out.println("-----------");

		}

		System.out.println("读取" + file.getName() + "成功,数据条数" + rowsList.size());
		String oldFileNmae = file.getName();
		String pathWithName = file.getAbsolutePath();
		String path = pathWithName.substring(0,
				pathWithName.indexOf(oldFileNmae));
		File tmpFile = new File(path + File.separator + r.getNo() + ".htm");
		if (!tmpFile.getName().equals(oldFileNmae)) {

			tmpFile.delete();
			System.out.println("删除重复的文件" + tmpFile.getName());

			file.renameTo(tmpFile);
		}

		System.out.println(oldFileNmae + "更名为" + tmpFile.getName());
		return rowsList;
	}

*/
	public static Report getReport(Node node) {
		String reportDate = "2000-10-10";
		String reportNo = "11111";
		Report report = new Report();

		// 通过getElementsByTagName获取Node
		try {
			NodeList nodeList = XPathAPI.selectNodeList(node, "//I");

			Element e = (Element) nodeList.item(0);
			String content = e.getTextContent().trim();
			reportNo = content;
			if (content.length() < 9)// 例如737564是曙光的,20161115-TY01-1-G0090628-E是仁济东院的,33902402是瑞金
			// 20161108I2000N86001是华山医院，5825331是公卫金山
			{
				NodeList divList = XPathAPI.selectNodeList(node, "//DIV");
				for (int i = 0; i < divList.getLength(); i++) {
					Element ediv = (Element) divList.item(i);
					String contentDate = ediv.getTextContent().trim();
					if (contentDate.indexOf("报告日期：") > -1) {
						int position = contentDate.indexOf("报告日期：");
						contentDate = contentDate.substring(position + 5,
								position + 15);
						report.setDate(contentDate);
						break;
					}

				}
			} else {

				reportDate = content.substring(0, 8).trim();
				report.setDate(reportDate);

			}

		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 每行的内容
			// report.setDate(reportDate);
		report.setNo(reportNo);
		return report;
	}

	/**
	 * 功能：Java读取txt文件的内容 步骤：1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流 4：一行一行的输出。readline()。 备注：需要考虑的是异常情况
	 * 
	 * @param filePath
	 */
	public static String readTxtFile(String filePath) {
		StringBuffer sb = new StringBuffer();
		try {

			String encoding = "utf-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					sb.append(lineTxt);
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static List<String> match(String testStr,String pattern) {
		List<String> list=new ArrayList();
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(testStr);
		while (m.find()) {
			list.add(m.group(1));
		}
		return list;
	}

	public static void updateHostpitalList() throws Exception {
		// TODO Auto-generated method stub
		String hostpitalhtml=QueryHttpClient.gethostpitalhtml();
		List<String> valuelist=Importer.match(hostpitalhtml, Const.pattern_hostpital_value);
		List<String> titlelist=Importer.match(hostpitalhtml, Const.pattern_hostpital_title);
		ImportDaoImple	im=new ImportDaoImple();
		im.updateHostpitalList(valuelist,titlelist);
	}
	public static List<Hospital> getReportNosk(String str) {

		try {
			// String str = Importer.readTxtFile("d:/tmp/table.txt");
			List<Hospital> list = new ArrayList<Hospital>();
			// "href=['\"]([^'\"]*)['\"]"
			Pattern p = Pattern.compile("<td>([^'\"]*)</td>");
			Matcher m = p.matcher(str);
			while (m.find()) {
				Hospital h=new Hospital();
				String tmp = m.group(1);
				String[] array = tmp.split("</td>\n        <td>");
				
				String hospital_name = array[1].trim();//取医院名称
				
				String 	num = array[0].trim();//取医院编号
				h.setHospital_name(hospital_name);
				h.setNum(num);
				System.out.println("sk查询的报告" + num+",医院名称"+hospital_name);
				list.add(h);
			}
			return list;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
